package site.teamo.biu.flink.web.configuration;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.pattern.PathPatternParser;
import site.teamo.biu.flink.web.configuration.user.UserInterceptor;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author haocongshun
 * @date 2023/10/30 13:54:47
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${biu-flink.swagger.enable}")
    private boolean swaggerEnable;
    @Resource
    private UserInterceptor userInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> swaggerPathPatterns = CollectionUtil.newArrayList(
                "/swagger-resources/**",
                "/webjars/**",
                "/v3/**",
                "/doc.html"
        );
        List<String> excludePathPatterns = CollectionUtil.newArrayList(
                "/api/passport/login",
                "/api/passport/is-login"
        );
        if (swaggerEnable) {
            excludePathPatterns.addAll(swaggerPathPatterns);
        }
        registry.addInterceptor(userInterceptor)
                .excludePathPatterns(excludePathPatterns);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (swaggerEnable) {
            registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    @Bean
    public CorsFilter corsFilter() {
        org.springframework.web.cors.CorsConfiguration config = new org.springframework.web.cors.CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
